package com.cn.activitiNSV.configuration.httpclient;


import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @Author: Eric
 **/
@Component
public class HttpClientHandler {

    private Logger logger = LoggerFactory.getLogger(HttpClientHandler.class);

    @Resource(name = "customHttpClientManagerFactoryBean")
    private CloseableHttpClient client;

    /**
     * 无参get请求
     */
    public HttpResult doGet(String url) {
        HttpEntity entity = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = client.execute(httpGet);
            entity = response.getEntity();
            HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity, Consts.UTF_8));
            EntityUtils.consumeQuietly(entity);
            return httpResult;
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            if (null != entity) {
                EntityUtils.consumeQuietly(entity);
            }
        }
        return null;
    }

    /**
     * 有参get请求
     */
    public HttpResult doGet(String url, Map<String, String> params) {
        URIBuilder uriBuilder;
        try {
            uriBuilder = new URIBuilder(url);
            if (params != null) {
                for (String key : params.keySet()) {
                    uriBuilder.setParameter(key, params.get(key));
                }
            }
            return this.doGet(uriBuilder.build().toString());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 有参post请求
     */
    public HttpResult doPost(String url, Map<String, String> params) {
        HttpEntity entity = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                List<NameValuePair> parameters = new ArrayList<>(1);
                for (String key : params.keySet()) {
                    parameters.add(new BasicNameValuePair(key, params.get(key)));
                }
                // 构造一个form表单式的实体
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
                // 将请求实体设置到httpPost对象中
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse response = client.execute(httpPost);
            entity = response.getEntity();
            HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity, Consts.UTF_8));
            EntityUtils.consumeQuietly(entity);
            return httpResult;
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            if (null != entity) {
                EntityUtils.consumeQuietly(entity);
            }
        }
        return null;
    }

    /**
     * 有参post请求,json交互
     */
    public HttpResult doPostJson(String url, String json) {
        HttpEntity entity = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            if (StringUtils.isNotBlank(json)) {
                StringEntity stringEntity = new StringEntity(json);
                stringEntity.setContentEncoding(Consts.UTF_8.toString());
                stringEntity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
                httpPost.setEntity(stringEntity);
            }
            CloseableHttpResponse response = client.execute(httpPost);
            entity = response.getEntity();
            HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(entity, Consts.UTF_8));
            EntityUtils.consumeQuietly(entity);
            return httpResult;
        } catch (ParseException | UnsupportedEncodingException | ClientProtocolException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            logger.error("HttpClient链接超时");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != entity) {
                EntityUtils.consumeQuietly(entity);
            }
        }
        return null;
    }

    /**
     * 无参post请求
     */
    public HttpResult doPost(String url) {
        return this.doPost(url, null);
    }
}
